import { useParams } from "react-router-dom";
import { getQuestions } from "../utils/api";
import { useRequest } from "ahooks";
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { resetComponents } from "../store/componentsReducer";
import { resetPageInfo } from "../store/pageInfoReducer";
const useLoadingQuestionData = () => {
  const { id = "" } = useParams();
  const dispatch = useDispatch();
  // const load = async () => {
  //   const res = await getQuestions(id);
  //   return res;
  // };

  // const { loading, data, error } = useRequest(load);
  // return { loading, data, error };
  const { loading, data, error, run } = useRequest(
    async (id: string) => {
      if (!id) throw new Error("无问卷");
      const data = await getQuestions(id);
      return data;
    },
    {
      manual: true,
    }
  );
  useEffect(() => {
    if (!data) return;
    const { title = "",desc='',js='',css='',isPublished=false, componentList = [] } = data;
    let selectId = "";
    if (componentList.length > 0) {
      selectId = componentList[0].fe_id;
    }
    dispatch(
      resetComponents({ componentList, selectId, copiedComponent: null })
    );
    dispatch(resetPageInfo({title ,desc,js,css,isPublished}))
  }, [data]);
  useEffect(() => {
    run(id);
  }, [id]);
  return { loading, error };
};

export default useLoadingQuestionData;
